package com.jyy.utils.dynamicdatasource.config;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.jyy.utils.dynamicdatasource.DynamicContextHolder;
import com.jyy.utils.dynamicdatasource.DynamicProperties;
import com.jyy.utils.dynamicdatasource.utils.DynamicDbUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多数据源
 *
 * @author jyy
 * @data 2025-01-14
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    /**
     * 目标数据源
     */
    public static Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(10);

    /**
     * 确定当前数据源
     *
     * @return 当前数据源
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicContextHolder.peek();
    }

    /**
     * 设置数据源
     *
     * @param dbKey             数据源key
     * @param dynamicProperties 数据源配置对象
     */
    public static void setDataSource(String dbKey, DynamicProperties dynamicProperties) {
        // 检查数据源是否存在
        if (!DynamicDataSource.targetDataSources.containsKey(dbKey)) {
            // 获取新的数据源
            DruidDataSource dataSource = DynamicDbUtil.getDbSourceByDbKey(dbKey, dynamicProperties);
            // 添加到targetDataSources中
            DynamicDataSource.targetDataSources.put(dbKey, dataSource);
        }
        // 将数据源放key入ThreadLocal中，
        DynamicContextHolder.push(dbKey);
        // 获取动态数据源Bean
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringUtil.getBean("dynamicDataSource");
        // 使得修改后的targetDataSources生效
        dynamicDataSource.afterPropertiesSet();
    }

}
